package io.vov.vitamio.widget;

import io.vov.vitamio.IMediaControl;
import io.vov.vitamio.MediaPlayer;
import io.vov.vitamio.VPlayerListener;
import io.vov.vitamio.utils.StringUtils;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.TextView;
import android.widget.Toast;

public abstract class BaseMediaController extends FrameLayout implements
		VPlayerListener {

	public int DEFAULT_TIME_OUT = 2000;
	protected ImageView mPlayOperationView;
	protected TextView mStartTimeView;
	protected TextView mEndTimeView;
	protected SeekBar mProgressBar;
	private boolean mInstantSeeking = false;
	private int mTimeOut = DEFAULT_TIME_OUT;

	private boolean mIsAutoPlay = false; // 是否为自动播放

	private OnClickListener mPlayClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			mInstantSeeking = true;
			if (mBufferComplete) {
				hideLoading();
			} else {
				showLoading();
			}

			if (mPlayer == null)
				return;

			boolean isPlay = !mPlayer.isPlaying();
			updatePlayState(isPlay);
			play(isPlay);
			v.setSelected(!isPlay);

			// 如果是已经播放完毕了。
			if (mPlayer.isPlayCompleted()) {
				show();
				setProgress(0);
			} else {
				hideWithTimeOut(mTimeOut);
			}

		}

	};

	private OnSeekBarChangeListener mSeekListener = new OnSeekBarChangeListener() {
		public void onStartTrackingTouch(SeekBar bar) {
			Log.d(VIEW_LOG_TAG, "onStartTrackingTouch");
			show();
			mInstantSeeking = true;
		}

		public void onProgressChanged(SeekBar bar, int progress,
				boolean fromuser) {
			if (!fromuser)
				return;
			Log.d(VIEW_LOG_TAG, "onProgressChanged");

			long newposition = (mPlayer.getDuration() * progress)
					/ bar.getMax();
			String time = StringUtils.generateTime(newposition);
			mPlayer.seekTo(newposition);
			if (mStartTimeView != null)
				mStartTimeView.setText(time);
		}

		public void onStopTrackingTouch(SeekBar bar) {
			Log.d(VIEW_LOG_TAG, "onStopTrackingTouch");
			mPlayer.seekTo((mPlayer.getDuration() * bar.getProgress())
					/ bar.getMax());
			postDelayed(new Runnable() {
				public void run() {
					hide();
				}
			}, mTimeOut);
		}
	};

	public BaseMediaController(Context context, AttributeSet attrs) {
		super(context, attrs);
		onCreateView();

		mPlayOperationView = getPlayOperationView();
		mStartTimeView = getStartTimeView();
		mEndTimeView = getEndTimeView();
		mProgressBar = getProgressBar();

		if (mPlayOperationView != null)
			mPlayOperationView.setOnClickListener(mPlayClickListener);

		if (mProgressBar != null)
			mProgressBar.setOnSeekBarChangeListener(mSeekListener);

	}

	public abstract SeekBar getProgressBar();

	public abstract View onCreateView();

	public abstract TextView getEndTimeView();

	public abstract TextView getStartTimeView();

	public abstract ImageView getPlayOperationView();

	public abstract int getPlayImageResource();

	public abstract int getPauseImageResource();

	protected IMediaControl mPlayer;
	private boolean mBufferComplete;

	@Override
	public void onHWRenderFailed() {
		// 不用实现
		showWithTimeOut();
	}

	@Override
	public void onSubChanged(String text) {
		// 不用实现
	}

	@Override
	public void onSubChanged(byte[] pixels, int width, int height) {
		// 不用实现
	}

	@Override
	public void onOpenStart() {
		// 准备开始播放
		showLoading();
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		showLoading();
	}

	@Override
	public void onOpenSuccess() {
		hideLoading();
	}

	@Override
	public void onOpenFailed(int f, int d) {
		showError(getString("rae_video_open_error"));
		showWithTimeOut();
		hideLoading();
	}

	@Override
	public void onBufferStart() {
		mBufferComplete = false;
		if (mInstantSeeking) {
			showWithTimeOut();
			showLoading();
		}
	}

	@Override
	public void onBufferComplete() {
		mBufferComplete = true;
		if (mInstantSeeking || mIsAutoPlay) {
			showWithTimeOut();
			hideLoading();
			play(true); // 播放
			updatePlayState(true); // 显示暂停按钮
			hideWithTimeOut(mTimeOut);
			mInstantSeeking = false;
		}

	}

	@Override
	public void onDownloadRateChanged(int kbPerSec) {

	}

	@Override
	public void onPlaybackComplete() {
		showWithTimeOut(); // 重新显示
		updatePlayState(false); // 显示播放按钮
	}

	@Override
	public void onCloseStart() {
		show();
	}

	@Override
	public void onCloseComplete() {
		show();
	}

	@Override
	public void onBufferingUpdate(MediaPlayer mp, int p) {
		// 不要求显示实时下载速度的不用实现
		if (mProgressBar != null)
			mProgressBar.setSecondaryProgress(p * 10);
	}

	@Override
	public void onSeekComplete(MediaPlayer mp) {
		// 不用实现
	}

	@Override
	public void onMedialControl(IMediaControl l) {
		mPlayer = l;
	}

	@Override
	public void onPlaying(long position, long duration, String startTime,
			String endTime) {
		Log.e("onPlaying==>", "onPlaying");
		if (mStartTimeView != null)
			mStartTimeView.setText(startTime);
		if (mEndTimeView != null)
			mEndTimeView.setText(endTime);

		// 进度显示
		if (mProgressBar != null && duration > 0) {
			long pos = mProgressBar.getMax() * position / duration;
			mProgressBar.setProgress((int) pos);
		}
	}

	public void showError(String msg) {
		if (TextUtils.isEmpty(msg))
			return;
		Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT).show();
	}

	public String getString(String resId) {
		try {
			int id = getResources().getIdentifier(resId, "string",
					getContext().getPackageName());
			if (id <= 0)
				return null;
			return getResources().getString(id);
		} catch (Exception e) {
			Log.e(VIEW_LOG_TAG, "获取资源出错：" + resId);
		}
		return null;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event) {
		Log.d(VIEW_LOG_TAG, "Action=" + event.getAction());
		int action = event.getAction();

		if (action == MotionEvent.ACTION_CANCEL
				|| action == MotionEvent.ACTION_UP) {
			showWithTimeOut();
			return true;
		}

		return super.onTouchEvent(event);
	}

	/**
	 * @param isPlay
	 *            当前状态,如果要显示播放按钮，则是false
	 */
	private void updatePlayState(boolean isPlay) {
		if (isPlay) { // 如果状态已经是播放，则设置为暂停
			Log.d(VIEW_LOG_TAG, "显示为暂停按钮");
			mPlayOperationView.setImageResource(getPauseImageResource());
		} else {// 如果状态已经是暂停，则设置为播放
			Log.d(VIEW_LOG_TAG, "显示为播放按钮");
			mPlayOperationView.setImageResource(getPlayImageResource());
		}
	}

	protected void play(boolean played) {
		if (played) {
			mPlayer.start();
		} else {
			mPlayer.stop();
		}
	}

	public void show(int timeout) {
		if (isShowed()) {
			Log.d(VIEW_LOG_TAG, "已经显示了~");

			// 如果现在已经在播放中，则准备隐藏
			if (isPlaying()) {
				Log.d(VIEW_LOG_TAG, "准备隐藏~");
				hideWithTimeOut(timeout);
			}
			return;
		}

		show(); // 显示控制面板

		Log.d(VIEW_LOG_TAG, "--》 是否正在播放：" + isPlaying());
		updatePlayState(isPlaying()); // 如果正在播放，则显示暂停。如果暂停，则显示播放。

		// 超时时间
		if (timeout > 0) {
			hideWithTimeOut(timeout);
		}
	}

	private void hideWithTimeOut(int timeout) {
		postDelayed(new Runnable() {
			@Override
			public void run() {

				// 已经播放完毕就不要隐藏了。
				if (mPlayer != null && mPlayer.isPlayCompleted()) {
					return;
				}
				if (isShowed() && mTimeOut > 0 && isPlaying()) {
					hide();
				}
			}
		}, timeout);
	}

	/**
	 * 当加载完毕后，是否自动播放
	 * 
	 * @param enabled
	 */
	public void setAutoPlay(boolean enabled) {
		mIsAutoPlay = enabled;
	}

	public void showWithTimeOut() {
		show(mTimeOut);
	}

	public abstract void show();

	public boolean isShowed() {
		return getVisibility() != View.GONE;
	}

	public abstract void hide();

	public abstract void showLoading();

	public abstract void hideLoading();

	protected boolean isPlaying() {
		if (mPlayer == null)
			return false;
		return mPlayer.isPlaying();
	}

	protected void setProgress(int i) {
		if (mProgressBar != null)
			mProgressBar.setProgress(i);
	}

	/**
	 * 设置自动隐藏时间，如果不想自动隐藏，设置小于0 就行了。
	 * 
	 * @param timeout
	 */
	public void setTimeOut(int timeout) {
		mTimeOut = timeout;
	}

}
